package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"time"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
)

type SiteController struct {
}

func SiteRegister(group *gin.RouterGroup) {
	site := &SiteController{}
	//创建场地
	group.POST("/add", site.Add)
	//场地列表
	group.GET("/page", site.Page)
	//普通用户获取场地列表
	group.GET("/site_page", site.SitePage)
	//获取场地详情
	group.GET("/detail", site.Detail)
	//修改场地
	group.POST("/update", site.Update)
	//修改场地状态
	group.POST("/update_status", site.UpdateStatus)
	//删除场地
	group.POST("/remove", site.Remove)
}

func (s *SiteController) Add(c *gin.Context) {
	params := &dto.SiteAddInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("创建场地失败,请稍后重试"), true)
		return
	}
	site := &dao.Site{
		Name:         params.Name,
		Address:      params.Address,
		Longitude:    params.Longitude,
		Latitude:     params.Latitude,
		Image:        params.Image,
		Phone:        params.Phone,
		MaxPeopleNum: params.MaxPeopleNum,
		Des:          params.Des,
		Facilities:   []byte(params.Facilities),
		Service:      []byte(params.Service),
		Options:      []byte(params.Options),
		Business:     params.Business,
		Sort:         params.Sort,
		Mark:         params.Mark,
	}
	if err := site.Save(c, tx); err != nil {
		middleware.ResponseError(c, 500, errors.New("创建场地失败,请稍后重试"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (s *SiteController) Page(c *gin.Context) {
	params := &dto.SitePageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败,请稍后重试"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Site
	query := tx.WithContext(c).Model(&dao.Site{}).Where("is_delete=0").Order("sort desc")
	if params.Type == "1" {
		query = query.Where("status = 0")
	}
	if params.Type == "2" {
		query = query.Where("status = 1")
	}
	if params.Type == "3" {
		query = query.Where("status = 2")
	}
	if params.Keyword != "" {
		query = query.Where("name LIKE ?", "%"+params.Keyword+"%")
	}
	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	out := &dto.SitePageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.SiteInfo{
			Id:           fmt.Sprintf("%d", item.Id),
			Name:         item.Name,
			Address:      item.Address,
			Longitude:    item.Longitude,
			Latitude:     item.Latitude,
			Image:        item.Image,
			MaxPeopleNum: item.MaxPeopleNum,
			Phone:        item.Phone,
			Des:          item.Des,
			Facilities:   string(item.Facilities),
			Options:      string(item.Options),
			Service:      string(item.Service),
			Business:     item.Business,
			Sort:         item.Sort,
			Status:       item.Status,
			IsDelete:     item.IsDelete,
			Mark:         item.Mark,
			CreatedAt:    item.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:    item.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, false)
}
func (s *SiteController) SitePage(c *gin.Context) {
	params := &dto.SitePageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败,请稍后重试"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Site
	centerLat, centerLng := params.Latitude, params.Longitude
	err = tx.Model(&dao.Site{}).Raw(`
        SELECT *,
            (6371 * acos(cos(radians(?)) * cos(radians(Latitude)) * cos(radians(Longitude) - radians(?)) + sin(radians(?)) * sin(radians(Latitude)))) AS distance
        FROM site
        WHERE is_delete = 0 AND status <> 1
        ORDER BY distance
        LIMIT ? OFFSET ?`,
		centerLat, centerLng, centerLat, params.PageSize, offset).Scan(&list).Error
	query := tx.WithContext(c).Model(&dao.Site{}).Where("is_delete=0 AND status <> 1").Order("sort desc")
	query.Count(&total)
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	out := &dto.SitePageOutput{
		Total: total,
	}
	now := time.Now().Format("2006-01-02 15:04:05")
	for _, item := range list {
		//查询场地是否被预约过
		reservation := &dao.Reservation{}
		tx.Where("site_id = ? AND is_delete = 0 AND status = 0 AND end_time > ? AND created_by = ?", item.Id, now, value).First(reservation)
		value := dto.SiteInfo{
			Id:           fmt.Sprintf("%d", item.Id),
			Name:         item.Name,
			Address:      item.Address,
			Longitude:    item.Longitude,
			Latitude:     item.Latitude,
			Image:        item.Image,
			MaxPeopleNum: item.MaxPeopleNum,
			Des:          item.Des,
			Facilities:   string(item.Facilities),
			Service:      string(item.Service),
			Options:      string(item.Options),
			Phone:        item.Phone,
			Business:     item.Business,
			Mark:         item.Mark,
			Sort:         item.Sort,
			Status:       item.Status,
			IsDelete:     item.IsDelete,
		}
		if reservation.Id != 0 {
			value.ReservationStatus = 1
		}
		out.List = append(out.List, value)
	}
	middleware.ResponseSuccess(c, out, false)
}
func (s *SiteController) Update(c *gin.Context) {
	params := &dto.SiteUpdateInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	if result := tx.Model(&dao.Site{}).Where(map[string]interface{}{
		"id": params.Id,
	}).Select("name", "address", "longitude", "latitude", "image", "max_people_num", "facilities", "service", "des", "business", "phone", "sort", "mark", "options").Updates(&dao.Site{
		Name:         params.Name,
		Address:      params.Address,
		Longitude:    params.Longitude,
		Latitude:     params.Latitude,
		Image:        params.Image,
		MaxPeopleNum: params.MaxPeopleNum,
		Des:          params.Des,
		Facilities:   []byte(params.Facilities),
		Service:      []byte(params.Service),
		Options:      []byte(params.Options),
		Business:     params.Business,
		Phone:        params.Phone,
		Mark:         params.Mark,
		Sort:         params.Sort,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (s *SiteController) Detail(c *gin.Context) {
	params := &dto.SiteDetailInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取详情失败"), true)
		return
	}
	site := &dao.Site{}
	if result := tx.Where(map[string]interface{}{
		"id": params.Id,
	}).First(site); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("获取详情失败"), true)
		return
	}
	middleware.ResponseSuccess(c, dto.SiteInfo{
		Id:           fmt.Sprintf("%d", site.Id),
		Name:         site.Name,
		Address:      site.Address,
		Longitude:    site.Longitude,
		Latitude:     site.Latitude,
		Image:        site.Image,
		Des:          site.Des,
		MaxPeopleNum: site.MaxPeopleNum,
		Facilities:   string(site.Facilities),
		Phone:        site.Phone,
		Service:      string(site.Service),
		Options:      string(site.Options),
		Business:     site.Business,
		Sort:         site.Sort,
		Mark:         site.Mark,
		Status:       site.Status,
		IsDelete:     site.IsDelete,
	}, false)
}
func (s *SiteController) UpdateStatus(c *gin.Context) {
	params := &dto.SiteUpdateStatusInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Site{}).Where("id = ?", params.Id).Update("status", params.Status); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (s *SiteController) Remove(c *gin.Context) {
	params := &dto.RemoveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Site{}).Where("id = ?", params.Id).Update("is_delete", 1); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
